package com.shundr.shipper.cargo;

import java.util.ArrayList;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.shundr.shipper.R;
import com.shundr.shipper.base.BaseFragment;
import com.shundr.shipper.cargo.adapter.CargoAdapter;
import com.shundr.shipper.cargo.dao.CargoDao;
import com.shundr.shipper.cargo.http.CargoRequest;
import com.shundr.shipper.cargo.model.CargoInfo;
import com.shundr.shipper.cargo.view.PopScreeingCargo;
import com.shundr.shipper.cargo.view.PopScreeingCargo.OnItemSelectedListener;
import com.shundr.shipper.common.http.CommonRequest;
import com.shundr.shipper.common.model.AttributeInfo;
import com.shundr.shipper.common.util.AttrUtil;
import com.shundr.shipper.common.util.CommonConfig;
import com.shundr.shipper.common.util.DateUtil;
import com.shundr.shipper.common.util.ProgressDialogHelper;
import com.shundr.shipper.common.util.ToastHelper;
import com.shundr.shipper.common.view.CListView;
import com.shundr.shipper.common.view.CListView.OnLoadMoreListener;
import com.shundr.shipper.common.view.CListView.OnRefreshListener;
import com.shundr.shipper.frame.constant.LContext;
import com.shundr.shipper.frame.http.LHttpRequest;
import com.shundr.shipper.frame.service.PhoneReceiver;
import com.shundr.shipper.frame.service.PhoneReceiver.PhoneHandler;
import com.shundr.shipper.frame.service.PushMessageReceiver;
import com.shundr.shipper.frame.service.PushMessageReceiver.ReceiverHandler;
import com.shundr.shipper.frame.util.StringUtil;
import com.shundr.shipper.route.RouteListActivity;
import com.shundr.shipper.user.LoginActivity;
import com.shundr.shipper.user.util.UserListener;
import com.shundr.shipper.user.util.UserUtil;

/**
 * 
 * CargoFragment 货源界面
 * 
 * @author larry 2015-4-13 上午11:01:04
 * @version 1.0.0
 *
 */
public class CargoFragment extends BaseFragment implements OnClickListener,
		ReceiverHandler, UserListener, PhoneHandler {

	private static final int PAGE_SIZE = LContext.PAGE_SIZE;
	private int pageNo = 0;

	private Drawable drbDown;
	private Drawable drbUp;

	// private LinearLayout mLayoutCategory;
	private LinearLayout mLayoutRoute;
	private TextView tvCount;
	private TextView tvContent;
	private TextView tvTime;

	private Button btnLength;
	private Button btnType;
	private Button btnWeight;

	private CListView mListView;
	private CargoAdapter mAdapter;

	private CargoDao mCargoDao;

	protected RelativeLayout mLayoutNoContent;
	protected TextView tvNoContent;

	private List<CargoInfo> mList = new ArrayList<CargoInfo>();

	private PopScreeingCargo mPopType;
	private PopScreeingCargo mPopLength;
	private PopScreeingCargo mPopWeight;
	/**
	 * 车辆长度code
	 */
	String TruckLengthCode = "null";
	/**
	 * 车辆类型code
	 */
	String TruckTypeCode = "null";
	/**
	 * 货物重量code
	 */
	String CargoWeightCode = "null";

	private String mStartCode = LContext.nullStr;
	private String mEndCode = LContext.nullStr;
	private String mStart = "全国";
	private String mEnd = "全国";

	@SuppressLint("HandlerLeak")
	private Handler mHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case CargoRequest.GET_CARGO_LIST_SUCCESSED:
				@SuppressWarnings("unchecked")
				List<CargoInfo> infos = (List<CargoInfo>) msg.obj;
				if (infos != null) {
					if (infos.size() > 0) {
						if (pageNo == 0) {
							mList.clear();
							mListView.setVisibility(View.VISIBLE);
							mLayoutNoContent.setVisibility(View.GONE);
							if (infos.size() >= PAGE_SIZE) {
								mListView.setCanLoadMore(true);
								mListView.setAutoLoadMore(true);
								mListView.setCanRefresh(true);
							} else {
								mListView.setCanLoadMore(false);
								mListView.setAutoLoadMore(false);
								mListView.setCanRefresh(false);
							}
						}
						mList.addAll(infos);
						mAdapter.notifyDataSetChanged();
						if (pageNo == 0) {
							mListView.setSelection(0);
							
						}
						pageNo = pageNo + 1;
					} else {
						if (pageNo == 0) {
							mListView.setVisibility(View.GONE);
							mLayoutNoContent.setVisibility(View.VISIBLE);
						} else {
							ToastHelper.toastLong(getActivity(), "最后一页");
						}
					}
				}
				
				if (pageNo == 0) {
					new CargoRequest(getActivity(), mHandler).getSearchCargoListNum("null",
							TruckTypeCode, TruckLengthCode, CargoWeightCode, mStartCode,
							mEndCode);
				}
				
				ProgressDialogHelper.dismiss();
				mListView.onRefreshComplete();
				mListView.onLoadMoreComplete();
				break;
			case LHttpRequest.REQUEST_FAILED:
				ProgressDialogHelper.dismiss();
				mListView.onLoadMoreComplete();
				mListView.onRefreshComplete();
				ToastHelper.toastShort(getActivity(), (String)msg.obj);
				break;
			default:
				break;
			}
			super.handleMessage(msg);
		}
	};

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
	}

	@SuppressLint("InflateParams")
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_cargo, null);
		initView(view);
		return view;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {//
		super.onActivityCreated(savedInstanceState);
		PhoneReceiver.mPhoneListeners.add(this);
		if (!StringUtil.isNull(getActivity().getIntent().getStringExtra("startCode"))) {
			mStartCode = getActivity().getIntent().getStringExtra("startCode");
		}
		if (!StringUtil.isNull(getActivity().getIntent().getStringExtra("endCode"))) {
			mEndCode = getActivity().getIntent().getStringExtra("endCode");
		}

		if (!StringUtil.isNull(getActivity().getIntent().getStringExtra(
				"srcPlace"))) {
			mStart = getActivity().getIntent().getStringExtra("srcPlace");
		}
		if (!StringUtil.isNull(getActivity().getIntent().getStringExtra(
				"destPlace"))) {
			mEnd = getActivity().getIntent().getStringExtra("destPlace");
		}
		ProgressDialogHelper.show(mContext, "正在加载中...");
		new CargoRequest(getActivity(), mHandler).getCargoLsit("null",
				TruckTypeCode, TruckLengthCode, CargoWeightCode, mStartCode,
				mEndCode, pageNo * PAGE_SIZE, PAGE_SIZE);
		submitSearch();
	}

	public void initView(View view) {
		// mLayoutCategory = (LinearLayout)
		// view.findViewById(R.id.layout_category);
		mLayoutRoute = (LinearLayout) view
				.findViewById(R.id.layout_route_often);
		tvCount = (TextView) view.findViewById(R.id.tv_route_count);
		tvContent = (TextView) view.findViewById(R.id.tv_route_often_content);
		tvTime = (TextView) view.findViewById(R.id.tv_route_often_time);
		btnLength = (Button) view.findViewById(R.id.btn_length);
		btnType = (Button) view.findViewById(R.id.btn_type);
		btnWeight = (Button) view.findViewById(R.id.btn_weight);
		btnLength.setOnClickListener(this);
		btnType.setOnClickListener(this);
		btnWeight.setOnClickListener(this);
		// mLayoutCategory.setOnClickListener(this);
		mLayoutRoute.setOnClickListener(this);
		mListView = (CListView) view.findViewById(R.id.lv_list);
		mAdapter = new CargoAdapter(mList, getActivity());
		mListView.setAdapter(mAdapter);
		mListView.setCanLoadMore(false);
		mListView.setAutoLoadMore(false);
		mListView.setCanRefresh(true);
		mListView.setOnRefreshListener(new OnRefreshListener() {

			@Override
			public void onRefresh() {
				pageNo = 0;
				new CargoRequest(getActivity(), mHandler).getCargoLsit("null",
						TruckTypeCode, TruckLengthCode, CargoWeightCode,
						mStartCode, mEndCode, pageNo * PAGE_SIZE, PAGE_SIZE);
			}
		});
		mListView.setOnLoadListener(new OnLoadMoreListener() {
			@Override
			public void onLoadMore() {
				new CargoRequest(getActivity(), mHandler).getCargoLsit("null",
						TruckTypeCode, TruckLengthCode, CargoWeightCode,
						mStartCode, mEndCode, pageNo * PAGE_SIZE, PAGE_SIZE);
			}
		});

		mLayoutNoContent = (RelativeLayout) view.findViewById(R.id.layout_no_content);
		tvNoContent = (TextView) view.findViewById(R.id.tv_no_content);
		listViewOnClick();
		drbDown = getResources().getDrawable(R.drawable.iv_arrow_up);
		// / 这一步必须要做,否则不会显示.
		drbDown.setBounds(0, 0, drbDown.getMinimumWidth(),drbDown.getMinimumHeight());

		drbUp = getResources().getDrawable(R.drawable.iv_arrow_down);
		// / 这一步必须要做,否则不会显示.
		drbUp.setBounds(0, 0, drbUp.getMinimumWidth(), drbUp.getMinimumHeight());

		initPopupWindow();
	}
	
	private String getSearch(){
		String search = mStart + " 到 " + mEnd + " : ";
		if(TruckLengthCode.equals(LContext.nullStr)){
			search = search + "不限";
		}else{
			search = search + btnLength.getText().toString();
		}
		if(TruckTypeCode.equals(LContext.nullStr)){
			search = search + "不限";
		}else{
			search = search + btnType.getText().toString();
		}
		if(CargoWeightCode.equals(LContext.nullStr)){
			search = search + "不限";
		}else{
			search = search + btnWeight.getText().toString();
		}
		return search;
	}
	
	private void submitSearch(){
		new CommonRequest(mContext, new Handler()).saveOperateHistory(CommonConfig.OPERATE_SEARCH, CommonConfig.OPERATE_OBJECT_CARGO, CommonConfig.OPERATE_SEARCH, getSearch());
	}

	public void onSearch(String startCode, String endCode) {
		pageNo = 0;
		mStartCode = startCode;
		mEndCode = endCode;
		new CargoRequest(getActivity(), mHandler).getCargoLsit("null",
				TruckTypeCode, TruckLengthCode, CargoWeightCode, mStartCode,
				mEndCode, pageNo * PAGE_SIZE, PAGE_SIZE);
	}

	/**
	 * listview点击事件
	 */
	private void listViewOnClick() {
		mListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
				if (LContext.isLogin()) {
					String cargoId = mList.get(position - 1).getCargoId() + "";
					Intent intent = new Intent(getActivity(),CargoDetailsActivity.class);
					intent.putExtra("CargoId", cargoId);
					startActivity(intent);
				} else {
					startActivity(new Intent(getActivity(), LoginActivity.class));
				}
			}
		});
	}

	/**
	 * 实例化popupwindow
	 */
	private void initPopupWindow() {
		mPopType = new PopScreeingCargo(mContext, AttrUtil.TYPE_TRUCK,
				new OnItemSelectedListener() {

					@Override
					public void onPopupWindowShow() {
						btnType.setCompoundDrawables(null, null, drbDown, null);
						btnType.setTextColor(getResources().getColor(R.color.cheng));
					}

					@Override
					public void onPopupWindowDismiss() {
						btnType.setCompoundDrawables(null, null, drbUp, null);
						btnType.setTextColor(getResources().getColor(R.color.light_black));
					}

					@Override
					public void onClick(AttributeInfo info) {
						TruckTypeCode = info.getCode();
						btnType.setText(info.getName());
						pageNo = 0;
						ProgressDialogHelper.show(mContext, "正在加载中...");
						new CargoRequest(getActivity(), mHandler).getCargoLsit(
								"null", TruckTypeCode, TruckLengthCode,
								CargoWeightCode, mStartCode, mEndCode, pageNo* PAGE_SIZE, PAGE_SIZE);
						submitSearch();
					}
				});

		mPopLength = new PopScreeingCargo(mContext, AttrUtil.TYPE_TRUCK_LENGTH,
				new OnItemSelectedListener() {

					@Override
					public void onPopupWindowShow() {
						btnLength.setCompoundDrawables(null, null, drbDown,null);
						btnLength.setTextColor(getResources().getColor(R.color.cheng));
					}

					@Override
					public void onPopupWindowDismiss() {
						btnLength.setCompoundDrawables(null, null, drbUp, null);
						btnLength.setTextColor(getResources().getColor(R.color.light_black));
					}

					@Override
					public void onClick(AttributeInfo info) {
						TruckLengthCode = info.getCode();
						btnLength.setText(info.getName());
						pageNo = 0;
						ProgressDialogHelper.show(mContext, "正在加载中...");
						new CargoRequest(getActivity(), mHandler).getCargoLsit(
								"null", TruckTypeCode, TruckLengthCode,
								CargoWeightCode, mStartCode, mEndCode, pageNo* PAGE_SIZE, PAGE_SIZE);
						submitSearch();
					}
				});

		mPopWeight = new PopScreeingCargo(mContext, AttrUtil.TYPE_CARGO_WEIGHT,
				new OnItemSelectedListener() {

					@Override
					public void onPopupWindowShow() {
						btnWeight.setCompoundDrawables(null, null, drbDown,null);
						btnWeight.setTextColor(getResources().getColor(R.color.cheng));
					}

					@Override
					public void onPopupWindowDismiss() {
						btnWeight.setCompoundDrawables(null, null, drbUp, null);
						btnWeight.setTextColor(getResources().getColor(R.color.light_black));
					}

					@Override
					public void onClick(AttributeInfo info) {
						CargoWeightCode = info.getCode();
						btnWeight.setText(info.getName());
						pageNo = 0;
						ProgressDialogHelper.show(mContext, "正在加载中...");
						new CargoRequest(getActivity(), mHandler).getCargoLsit(
								"null", TruckTypeCode, TruckLengthCode,
								CargoWeightCode, mStartCode, mEndCode, pageNo* PAGE_SIZE, PAGE_SIZE);
						submitSearch();
					}
				});

	}

	@Override
	public void onDestroy() {
		mHandler.removeCallbacksAndMessages(null);
		super.onDestroy();
		UserUtil.mUserListeners.remove(this);
		PushMessageReceiver.mReceiverListeners.remove(this);
		PhoneReceiver.mPhoneListeners.remove(this);
		mPopType.dismiss();
		mPopLength.dismiss();
		mPopWeight.dismiss();
		drbUp = null;
		drbDown = null;
	}

	@Override
	public void onPause() {
		super.onPause();
	}

	@Override
	public void onResume() {
		super.onResume();
		mCargoDao = new CargoDao();
		PushMessageReceiver.mReceiverListeners.add(this);
		UserUtil.mUserListeners.add(this);
	}

	private void dismissOther(int flag) {
		if (flag == 0) {
			if (mPopType.isShowing()) {
				mPopType.dismiss();
			}
			if (mPopWeight.isShowing()) {
				mPopWeight.dismiss();
			}
		} else if (flag == 1) {
			if (mPopLength.isShowing()) {
				mPopLength.dismiss();
			}
			if (mPopWeight.isShowing()) {
				mPopWeight.dismiss();
			}
		} else if (flag == 2) {
			if (mPopLength.isShowing()) {
				mPopLength.dismiss();
			}
			if (mPopType.isShowing()) {
				mPopType.dismiss();
			}
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_length:
			// 长度
			dismissOther(0);
			if (mPopLength.isShowing()) {
				mPopLength.dismiss();
			} else {
				mPopLength.showPopupWindow(v);
			}
			break;
		case R.id.btn_type:
			// 类型
			dismissOther(1);
			if (mPopType.isShowing()) {
				mPopType.dismiss();
			} else {
				mPopType.showPopupWindow(v);
			}
			break;
		case R.id.btn_weight:
			// 重量
			dismissOther(2);
			if (mPopWeight.isShowing()) {
				mPopWeight.dismiss();
			} else {
				mPopWeight.showPopupWindow(v);
			}
			break;
		case R.id.layout_route_often:
			if (LContext.isLogin()) {
				startActivity(new Intent(mContext, RouteListActivity.class));
			}
			break;
		default:
			break;
		}
	}

	public void initRoute() {
		int count = mCargoDao.getNoReadCount();
		if (count > 0) {
			mLayoutRoute.setVisibility(View.VISIBLE);
			tvCount.setText(count + "");
			CargoInfo info = mCargoDao.getFirst();
			if (info == null) {
				return;
			}
			String content = info.getCargoSrcPlace() + " 到  "+ info.getCargoDstPlace();
			tvContent.setText(content);
			tvTime.setText(DateUtil.getInterval(info.getCargoInsertTime()));
		} else {
			mLayoutRoute.setVisibility(View.GONE);
		}
	}

	@Override
	public void onReceived(int type) {
//		int count = mCargoDao.getNoReadCount();
//		if (count > 0) {
//			mLayoutRoute.setVisibility(View.VISIBLE);
//			tvCount.setText(count + "");
//			CargoInfo info = mCargoDao.getFirst();
//			if (info == null) {
//				return;
//			}
//			String content = info.getCargoSrcPlace() + " 到  "+ info.getCargoDstPlace();
//			tvContent.setText(content);
//		}
	}

	@Override
	public void onUserChanged(int flag) {
//		if (flag == 0) {// 登录
		// mLayoutRoute.setVisibility(View.VISIBLE);
//			initRoute();
//		} else if (flag == 1) {// 注销
//			mLayoutRoute.setVisibility(View.GONE);
//		}
	}

	@Override
	public void onPhoned() {
	}
}
